<script setup>
import {
  ref,
  onMounted,
  watch,
  onCreated,
  computed
} from 'vue'
import pdf from 'vue-pdf'
import {
  noticeFileUpload,
  noticeFileDownload
} from '@/api/wisdomBuild'
import { isAdmin } from '@/utils/permission/index'
import {
  handleDaochu,
  downloadOneFile,
  editShenHeStatus
} from '@/api/projectRecord'
const docx = require('docx-preview')
const props = defineProps({
  detailData: {
    type: Object,
    default: {}
  },
  pkid: {
    type: String
  },
  type: {
    type: String
  },
  isDefaultTab: {
    type: Boolean,
    default: true
  },
  canDaoChu: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['changeFile'])
const detailForm = ref(props.detailData)
// detailForm.value.projectClPoList[0].projectClFilePoList[0].name = detailForm.value.projectClPoList[0].projectClFilePoList[0].fileName
watch(
  detailForm,
  (newV, oldV) => {
    console.log('detailForm改变了', newV)
    emit('changeFile', newV)
  },
  { deep: true }
)
const isAdminUser = isAdmin()
const selectPkId = ref(0)
const fileName = ref('')
const pdfUrl = ref()
const dialogVisible = ref(false)
// const onPreview = (file) => {
//   // 预览
//   console.log(file)
//   fileName.value = getFileType(
//     file.name ? file.name : file.fileName
//   )
//   dialogVisible.value = true
//   if (file.fileId) {
//     downloadFile(file.fileId)
//   } else if (file.pkid) {
//     downloadFile(file.pkid)
//   }
// }
const onPreview = (file) => {
  console.log(file)
  xiazai(file)
}
const xiazai = (file) => {
  downloadOneFile(file).then((res) => {
    downloadDaochu(
      res,
      file.fileName ? file.fileName : file.name
    )
  })
}
const downloadFile = (id) => {
  // 预览
  noticeFileDownload(id).then((res) => {
    console.log(res, fileName)
    if (
      fileName.value === 'doc' ||
      fileName.value === 'docx'
    ) {
      docx.renderAsync(
        res,
        document.getElementById('yulan')
      )
    } else if (fileName.value === 'pdf') {
      pdfUrl.value = getObjectURL(res)
    }
  })
}
const getObjectURL = (file) => {
  let url = null
  if (window.createObjectURL !== undefined) {
    // basic
    url = window.createObjectURL(file)
  } else if (window.webkitURL !== undefined) {
    // webkit or chrome
    try {
      url = window.webkitURL.createObjectURL(file)
    } catch (error) {}
  } else if (window.URL !== undefined) {
    // mozilla(firefox)
    try {
      url = window.URL.createObjectURL(file)
    } catch (error) {}
  }
  return url
}
const beforeUpload = (file) => {
  file = file.file
  const param = new FormData()
  param.append('file', file)
  console.log(param.get('file'))
  noticeFileUpload(param).then(async (res) => {
    console.log(res)
    await detailForm.value.projectClPoList
      .find((item) => item.pkid == selectPkId.value)
      .projectClFilePoList.push({
        name: file.name,
        fileId: res.data
      })
    console.log(detailForm)
  })
}
const beforeUploadSize = (file) => {
  // if (file.size / (1024 * 1024) > 10) {
  //   // 限制文件大小
  //   alert('当前限制文件大小不能大于10M')
  //   return false
  // }
}
const getFileType = (name) => {
  console.log(name)
  const startIndex = name.lastIndexOf('.')
  if (startIndex !== -1) {
    return name.slice(startIndex + 1).toLowerCase()
  } else {
    return ''
  }
}
const shangchuan = (item) => {
  selectPkId.value = item.pkid
}
const onRemove = (file, fileList) => {
  // console.log(file,fileList,detailForm)
  // console.log(detailForm.value.projectClPoList.find(item=>item.pkid == file.clId).projectClFilePoList)
  const arr = detailForm.value.projectClPoList.find(
    (item) => item.pkid == file.clId
  ).projectClFilePoList
  console.log(arr, detailForm)
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].fileId == file.fileId) {
      console.log('删这个', arr[i])
      arr.splice(i, 1)
    }
  }
}
const daochu = () => {
  // alert('导出')
  handleDaochu({
    pkid: props.pkid,
    stage: props.detailData.projectClPoList[0].stage
  }).then((res) => {
    downloadDaochu(
      res,
      props.detailData.project.projectName +
        '-' +
        '附件导出.zip'
    )
  })
}
const downloadDaochu = (data, fileName) => {
  const blob = new Blob([data]) // 把得到的结果用流对象转一下
  console.log(blob)
  const a = document.createElement('a') // 创建一个<a></a>标签
  a.href = URL.createObjectURL(blob) // 将流文件写入a标签的href属性值
  a.download = fileName // 设置文件名
  a.style.display = 'none' // 障眼法藏起来a标签
  document.body.appendChild(a) // 将a标签追加到文档对象中
  a.click() // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
  a.remove() // 一次性的，用完就删除a标签
  //  }
}
const hebing = (category, index) => {
  let aa =
    detailForm.value.projectClPoList.findIndex(
      (itemForm) => itemForm.category == category
    ) == index
  // :rowspan="detailForm.projectClPoList.map(itemForm => itemForm.category == item.category).length"
  //   v-if="detailForm.projectClPoList.findIndex(itemForm => itemForm.category == item.category) == index"
  // console.log(aa)
  return aa
}
const hebingLength = (category) => {
  let bb = detailForm.value.projectClPoList.filter(
    (itemForm) => {
      return itemForm.category == category
    }
  ).length
  // console.log(bb)
  return bb
}
let checkStatusModel = ref({})
const changeCheckStatus = (event) => {
  let param = {}
  console.log(event)
  checkStatusModel.value.checkStatus = event
  param.checkStatus = event
  param.stage = props.detailData.projectClPoList[0].stage
  param.projectId = props.pkid
  param.clId = checkStatusModel.value.pkid
  // data.pkid
  editShenHeStatus(param).then((res) => {})
}
const changeCheckStatusModel = (data) => {
  checkStatusModel.value = data
}
</script>
<template>
  <div class="table-wrap">
    <div class="attachment-form">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div class="attachment-form-title">相关材料</div>
        <div
          style="color: #00baff; cursor: pointer"
          @click="daochu"
          v-if="canDaoChu"
        >
          导出
        </div>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th>序号</th>
            <th>材料类型</th>
            <th>材料名称</th>
            <th style="width: 40%">上传文件</th>
            <th>编辑状态</th>
            <th
              style="width: 20%"
              v-if="type == 'edit' && isDefaultTab"
            >
              操作
            </th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(
              item, index
            ) in detailForm.projectClPoList"
            :key="index"
          >
            <td>{{ item.rank }}</td>
            <td
              :rowspan="hebingLength(item.category)"
              v-if="hebing(item.category, index)"
            >
              {{ item.category }}
            </td>
            <td>{{ item.name }}</td>
            <td style="">
              <el-upload
                class="upload"
                :http-request="beforeUpload"
                :on-preview="onPreview"
                :on-remove="onRemove"
                :file-list="item.projectClFilePoList"
                :before-upload="beforeUploadSize"
                action="#"
                style="position: relative"
                :disabled="
                  !isDefaultTab ||
                  type == 'shenhe' ||
                  type == 'detail'
                "
                accept=".doc,.docx,.pdf,.png,.jpg,.jpeg,.dwg,.mp4,.gif"
                multiple
              >
                <!-- <el-button
                  type="text"
                  @click.stop="shenhefujian(item)"
                  class="fileUpload"
                  style="left: -80px"
                  v-if="
                    type == 'edit' &&
                    isDefaultTab &&
                    isAdminUser
                  "
                >
                  <span
                    class="upload-text"
                    :style="{
                      color:
                        item.checkStatus == '2'
                          ? 'red'
                          : '',
                      height: '100%'
                    }"
                    @click.stop="shenhefujian(item)"
                    >{{
                      item.checkStatus == '2'
                        ? '退回'
                        : '通过'
                    }}</span
                  >
                </el-button> -->
                <el-button
                  type="text"
                  @click="shangchuan(item)"
                  class="fileUpload"
                  v-if="
                    type == 'edit' &&
                    isDefaultTab &&
                    // 非管理员用户时退回状态才显示
                    // 管理员用户时都显示
                    ((!isAdminUser &&
                      item.checkStatus == '3') ||
                      isAdminUser)
                  "
                >
                  <span class="upload-icon"></span>
                  <span
                    class="upload-text"
                    :class="
                      isDefaultTab
                        ? ''
                        : 'upload-text-disabled disabled'
                    "
                    style="margin-left: 10px"
                    >点击上传</span
                  >
                </el-button>
              </el-upload>
            </td>
            <td>
              <span
                v-if="!isAdminUser || type === 'detail'"
              >
                {{
                  item.checkStatus == '2'
                    ? '通过'
                    : '待提交'
                }}
              </span>
              <el-dropdown
                v-else
                @command="changeCheckStatus"
                @visible-change="
                  changeCheckStatusModel(item)
                "
              >
                <span class="el-dropdown-link">
                  {{
                    item.checkStatus == '2'
                      ? '通过'
                      : '待提交'
                  }}<i
                    class="el-icon-arrow-down el-icon--right"
                  ></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="2"
                    >通过</el-dropdown-item
                  >
                  <el-dropdown-item command="3"
                    >待提交</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </td>
            <td v-if="type == 'edit' && isDefaultTab">
              <div class="table-btn">
                <!-- <div class="table-btn-item">上传</div> -->
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      title="文件预览"
      width="50%"
      top="60px"
      :modal="false"
    >
      <div
        ref="file"
        id="yulan"
        v-if="fileName === 'doc' || fileName === 'docx'"
      ></div>
      <pdf :src="pdfUrl" v-if="fileName === 'pdf'"></pdf>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
::v-deep .el-upload {
  position: absolute !important;
  right: -53% !important;
  top: 50% !important;
  transform: translate(50%, -50%) !important;
  &-list {
    &__item {
      margin-top: 0px;
      .el-upload-list__item-name {
        :first-child {
          margin-top: 8px;
        }
        :last-child {
          margin-bottom: 8px;
        }
      }
      .el-upload-list__item-status-label {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
      }
      .el-icon-close {
        // position: absolute;
        top: 50% !important;
        transform: translateY(-50%) !important;
      }
    }
  }
}
.upload {
  //   .el-upload-list--text{
  //   position: absolute !important;
  //   right: -25% !important;
  //   top: 50% !important;
  //   transform: translate(50%,-50%) !important;
  // }
  cursor: pointer;
  // height: 0px;

  &-text {
    // position: absolute;
    // top: -35px;
    // left: 260px;
    color: #00baff;
    // display: none;
  }

  &-icon {
    // position: absolute;
    position: absolute !important;
    right: -53% !important;
    top: 50% !important;
    transform: translate(50%, -50%) !important;
    width: 16px;
    height: 14px;
    // top: -22px;
    // left: 240px;
    background: url('~@/assets/images/wisdom-construction/upload-file.png');
    background-size: 100% 100%;
  }
  &-deactive-icon {
    position: absolute !important;
    right: -25% !important;
    top: 50% !important;
    transform: translate(50%, -50%) !important;
    width: 16px;
    height: 14px;
  }
  &-text-disabled {
    color: rgb(176, 176, 176);
  }
  .fileUpload {
    position: absolute !important;
    right: -25% !important;
    top: 50% !important;
    transform: translate(50%, -50%) !important;
  }

  .el-upload-list__item {
    margin-top: 0px !important;
  }
}
.attachment-form {
  padding: 0 27px;
  &-title {
    color: #4c565c;
    display: flex;
    align-items: center;
    margin: 18px 0 14px 0;
    font-size: 16px;
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 14px;
      background: linear-gradient(180deg, #40ebff, #bcf8ff);
      margin-right: 7px;
    }
  }
  .table {
    border-collapse: collapse;
    width: 100%;
    box-sizing: border-box;
    margin-left: 7px;
    thead {
      background-color: #f2f6fb;
    }
    td,
    th {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #6b767d;
      line-height: 42px;
      border: 1px solid #f2f6fb;
      text-align: center;
    }
    td {
      font-weight: normal;
    }
    tbody {
      tr {
        td {
          &:nth-child(1) {
            width: 50px;
          }
          &:nth-child(2) {
            width: 300px;
          }
          &:nth-child(3) {
            width: 300px;
          }
          &:nth-child(4) {
            max-width: 1000px;
          }
          &:nth-child(5) {
            width: 300px;
          }
        }
      }
    }
  }
}
.disabled {
  cursor: default;
}
</style>
